package com.ruitu.mall_98.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.MyRefreshBaseActivity;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.base.my_base.base_list.SuperViewHolder;
import com.beanu.arad.utils.AnimationUtil;
import com.beanu.arad.utils.TimeUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.utils.UIUtils;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.ruitu.mall_98.R;
import com.ruitu.mall_98_1.dao.api.APIRetrofit;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.PageModel;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.app.Msg;
import com.ruitu.router_module.utils.RcvUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

//系统消息列表
public class SysMsgListActivity extends MyRefreshBaseActivity {
    private TextView tv_empty;//空白页面

    private int currPage = 1;
    private int totalPage = 1;
    private int currPosition;//当前点击的位置

    private List<Msg> msgList = new ArrayList<>();
    private MsgListAdapter adapter;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    protected int getLayoutRes() {
        return R.layout.activity_sys_msg_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv_empty = findViewById(R.id.tv_empty);
        setHeadTitle("系统消息");
        showProgress();
        reqDataList();

//        tv_right_text.setTextColor(getResources().getColor(R.color.text_blue));
        setRightText("操作");
        initQQPop();
        RcvUtils.refreshCompleteDelay(lRecyclerView, null);
        Arad.bus.register(this);
    }

    @Override
    protected void onRightTextClick() {
        if (window.getVisibility() != View.VISIBLE) {
            showOrHideWindow(true);
        }
    }

    private void reqDataList() {//请求数据列表
        APIRetrofit.getDefault().reqMsgList(AppHolder.instance().getUser().getAccountId(), currPage, PAGE_SIZE)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<PageModel<Msg>>>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        e.printStackTrace();
                        tv_empty.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onNext(BaseResult<PageModel<Msg>> pageResult) {
                        hideProgress();
                        if (pageResult.isSuccess()) {
                            currPage = pageResult.getData().getCurrentPage();
                            totalPage = pageResult.getData().getTotalPage();
                            List<Msg> newData = pageResult.getData().getDataList();
                            msgList.addAll(newData);
                            adapter.setDataList(msgList);
                            if (isDataEmpty(msgList)) {
                                tv_empty.setVisibility(View.VISIBLE);
                            } else {
                                tv_empty.setVisibility(View.GONE);
                            }
                        } else {
                            ToastUtils.showShort(pageResult.getMsg());
                            tv_empty.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }

    // type(0, 删除单条  1,全部删除  2 全部已读)
    private void handleMsg(String id, int type) {
        APIRetrofit.getDefault().handleSystemMsg(id, AppHolder.instance().getUser().getAccountId(), type)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        hideProgress();
                        if (baseResult.isSuccess()) {
                            ToastUtils.showShort("操作成功");
                            lRecyclerView.forceToRefresh();
                        } else {
                            ToastUtils.showShort(baseResult.getMsg());
                        }
                    }
                });
    }

    @Override
    protected void onItemClick(View v, int position) {
        Bundle bundle = new Bundle();
        bundle.putString("msg_id", msgList.get(position).getId());
        startActivity(SysMsgDetailActivity.class, bundle);

        currPosition = position;
    }

    @Override
    protected void onItemLongClick(View v, final int position) {
        UIUtils.showAlertDialog(getSupportFragmentManager()
                , "温馨提示", "您确定要删除此条消息？"
                , "确定", "取消"
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        currPosition = position;
                        if (CommonUtils.isLoginToActivity(SysMsgListActivity.this)) {
                            hideProgress();
                            showProgressWithText(true, "正在删除");
                            handleMsg(msgList.get(position).getId(), 0);
                        } else {
                            ToastUtils.showShort("请先登录");
                        }
                    }
                }, null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetEvent(EventModel e) {
        if (e.getEventCode() == 18122851) {//消息已读
            msgList.get(currPosition).setMsgStatus("1");//0 未读  1 已读
            adapter.notifyItemChanged(currPosition);
        }
    }

    @Override
    protected RecyclerView.Adapter initAdapter() {
        adapter = new MsgListAdapter(this);
        return adapter;
    }

    @Override
    protected LRecyclerView findRecyclerView() {
        return findViewById(R.id.rcv_msg);
    }

    @Override
    protected void reqFirst() {
        msgList.clear();
        currPage = 1;
        reqDataList();
    }

    @Override
    protected void reqMore() {
        currPage++;
        if (currPage > totalPage) {
            refreshNoMoreData();
        } else {
            reqDataList();
        }
    }

    private TextView tv_all_read;//全部已读
    private TextView tv_all_del;//全部清空
    private View window;

    private void initQQPop() {
        window = findViewById(R.id.window);
        tv_all_read = window.findViewById(R.id.tv_all_read);
        tv_all_del = window.findViewById(R.id.tv_all_del);
        tv_all_read.setOnClickListener(this);
        tv_all_del.setOnClickListener(this);
        window.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_all_read) {
            UIUtils.showAlertDialog(getSupportFragmentManager(), "温馨提示", "是否全部标记为已读?",
                    "确定", "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showOrHideWindow(false);
                            hideProgress();
                            showProgressWithText(true, "正在修改");
                            handleMsg("", 2);//全部已读
                        }
                    }, null);
        }
        if (v == tv_all_del) {
            UIUtils.showAlertDialog(getSupportFragmentManager(), "温馨提示", "是否删除全部消息?",
                    "确定", "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showOrHideWindow(false);
                            showProgressWithText(true, "正在删除");
                            handleMsg("", 1);//全部清空
                        }
                    }, null);
        }
        if (v == window) {
            showOrHideWindow(false);
        }
    }

    private void showOrHideWindow(boolean isShow) {
        if (isShow) {
            AnimationUtil.startAlphaAnima(window, 0, 1);
            window.setVisibility(View.VISIBLE);
        } else {
            AnimationUtil.startAlphaAnima(window, 1, 0);
            window.setVisibility(View.GONE);
        }
    }

    private class MsgListAdapter extends ListBaseAdapter<Msg> {

        public MsgListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.home_item_msg_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            View flag_unread = holder.getView(R.id.flag_unread);
            TextView tv_title = holder.getView(R.id.tv_title);
            TextView tv_time = holder.getView(R.id.tv_time);
            TextView tv_content = holder.getView(R.id.tv_content);
            Msg msg = msgList.get(position);
            if (TextUtils.equals(msg.getMsgStatus(), "1")) {//0 未读 1 已读
                flag_unread.setVisibility(View.INVISIBLE);
            } else {
                flag_unread.setVisibility(View.VISIBLE);
            }
            tv_title.setText(msg.getTitle());
            tv_content.setText(msg.getContent());
            try {
                String time = TimeUtils.getFriendlyTimeSpanByNow(Long.parseLong(msg.getCreateTime()));
//                tv_time.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm")
//                        .format(Long.parseLong(msg.getCreateTime())));
                tv_time.setText(time);
            } catch (Exception e) {
                e.printStackTrace();
                tv_time.setText("1970-01-01 08:00:00");
            }
        }
    }

    protected void reReq() {
    }

    protected void reqData() {
    }

    protected ProgressLayout findProgressLayout() {
        return null;
    }
}
